package br.com.mftc.efitness.seguranca;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import br.com.mftc.efitness.beans.LoginBean;

@WebFilter("*.xhtml")
public class LoginAutenticadoFilter implements Filter {

	private static final String[] arquivosEscape = { "javax.faces.resource", "index.xhtml" };

	public void init(FilterConfig filterConfig) throws ServletException {

	}

	public void destroy() {

	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpSession httpSession = httpServletRequest.getSession();

		if (verificaPaginaInicial(request)) {
			chain.doFilter(request, response);
		} else {
			if (httpSession == null || httpSession.getAttribute("login") == null || ((LoginBean) httpSession.getAttribute("login")).getUsuario() == null) {
				RequestDispatcher requestDispatcher = request.getRequestDispatcher("/index.xhtml");
				requestDispatcher.forward(request, response);
			} else {
				chain.doFilter(request, response);
			}
		}
	}

	protected boolean verificaPaginaInicial(ServletRequest request) {
		String resource = ((HttpServletRequest) request).getRequestURI();
		for (String escape : arquivosEscape) {
			if (resource.contains(escape)) {
				return true;
			}
		}
		return false;
	}
}
